package com.hm.pan.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.hm.pan.annotation.CheckLogin;
import com.hm.pan.model.ResultObj;
import com.hm.pan.model.User;
import com.hm.pan.model.UserFile;
import com.hm.pan.service.UserFileService;
import com.hm.pan.util.StringUtil;

@RestController
@RequestMapping("userfile")
@CheckLogin
public class UserFileController {

	@Resource
	private UserFileService userFileService;

	/**
	 * 获取所有文件
	 */
	@GetMapping("getAllFiles")
	public Object getAllFiles(@RequestParam(name = "path", defaultValue = "/") String path,
			@RequestParam(name = "sortOrder", required = false, defaultValue = "ASC") String sortOrder,
			@RequestParam(name = "sortColumn", required = false, defaultValue = "filename") String sortColumn,
			HttpSession session) {
		User user = (User) session.getAttribute("user");

		ResultObj result = new ResultObj();
		try {
			UserFile filter = new UserFile();
			filter.setSortOrder(sortOrder);
			filter.setColumnName(sortColumn);
			filter.setUserId(user.getUserId());
			filter.setIsDelete(false);
			fixFilter(filter);

			result.setData(userFileService.getAllFilesByPath(path, filter));
			result.setStatusCode(200);
			result.setMessage("查询成功");
		} catch (Exception e) {
			result.setStatusCode(500);
			result.setMessage("查询失败");
			e.printStackTrace();
		}

		return result;
	}

	/**
	 * 根据分类取所有文件
	 */
	@GetMapping("getByCategory")
	public Object getFilesByCategory(@RequestParam("category") String category,
			@RequestParam(name = "sortOrder", required = false, defaultValue = "ASC") String sortOrder,
			@RequestParam(name = "sortColumn", required = false, defaultValue = "filename") String sortColumn,
			HttpSession session) {
		User user = (User) session.getAttribute("user");
		Long userId = user.getUserId();
		ResultObj result = new ResultObj();
		String searchOption = null;

		{
			boolean flag = true;

			if (StringUtil.isEmpty(category)) {
				flag = false;
			} else {
				switch (category) {
				case "image":
					searchOption = "\\.(jpg|png|gif|bmp|jpeg|jpe|ico)$";
					break;
				case "video":
					searchOption = "\\.(mp4|avi|rmvb|3gp|flv|wmv|mpg)$";
					break;
				case "music":
					searchOption = "\\.(mp3|ape|wav|arm|mid|ogg)$";
					break;
				case "doc":
					searchOption = "\\.(docx?|dot|wps|xlsx?|pptx?|txt|pdf)$";
					break;
				default:
					flag = false;
					break;
				}
			}

			if (!flag) {
				result.setStatusCode(400);
				result.setMessage("category参数错误");
				return result;
			}
		}

		try {
			UserFile filter = new UserFile();
			filter.setSortOrder(sortOrder);
			filter.setColumnName(sortColumn);
			filter.setUserId(userId);
			filter.setIsDelete(false);
			filter.setUserId(user.getUserId());
			filter.setSearchOption(searchOption);
			fixFilter(filter);

			result.setData(userFileService.getAllFiles(filter));
			result.setStatusCode(200);
			result.setMessage("查询成功");
		} catch (Exception e) {
			result.setStatusCode(500);
			result.setMessage("获取失败");
			e.printStackTrace();
		}

		return result;
	}

	/**
	 * 获取回收站所有文件
	 */
	@GetMapping("getRecycle")
	public Object getRecycle(@RequestParam(name = "sortOrder", required = false, defaultValue = "ASC") String sortOrder,
			@RequestParam(name = "sortColumn", required = false, defaultValue = "filename") String sortColumn,
			HttpSession session) {
		User user = (User) session.getAttribute("user");
		ResultObj result = new ResultObj();

		try {
			UserFile filter = new UserFile();
			filter.setSortOrder(sortOrder);
			filter.setColumnName(sortColumn);
			filter.setUserId(user.getUserId());
			fixFilter(filter);

			result.setData(userFileService.getRecycle(filter));
			result.setStatusCode(200);
			result.setMessage("查询成功");
		} catch (Exception e) {
			result.setStatusCode(500);
			result.setMessage("查询失败");
			e.printStackTrace();
		}

		return result;
	}

	/**
	 * 删除文件或文件夹 如果不在回收站，删除到回收站，在回收站则永久删除
	 */
	@GetMapping("deleteFile")
	public Object deleteFile(@RequestParam(name = "userfileId") Long userfileId, HttpSession session) {
		User user = (User) session.getAttribute("user");
		ResultObj result = new ResultObj();

		if (userfileId == null) {
			result.setStatusCode(400);
			result.setMessage("参数有误");
			return result;
		}

		try {
			UserFile filter = new UserFile();
			filter.setUserfileId(userfileId);
			filter.setUserId(user.getUserId());
			UserFile file = userFileService.getOneFile(filter);

			if (file != null && userFileService.deleteFile(file.getIsDelete(), file.getUserfileId())) {
				result.setStatusCode(200);
				result.setMessage("删除成功");
			} else {
				result.setStatusCode(500);
				result.setMessage("删除失败");
			}
		} catch (Exception e) {
			result.setStatusCode(500);
			result.setMessage("删除失败");
			e.printStackTrace();
		}

		return result;
	}

	/**
	 * 从回收站还原一个文件
	 */
	@GetMapping("restoreFile")
	public Object restoreFile(@RequestParam(name = "userfileId") Long userfileId, HttpSession session) {
		User user = (User) session.getAttribute("user");
		ResultObj result = new ResultObj();

		if (userfileId == null) {
			result.setStatusCode(400);
			result.setMessage("参数有误");
			return result;
		}

		try {
			UserFile filter = new UserFile();
			filter.setUserfileId(userfileId);
			filter.setUserId(user.getUserId());
			UserFile file = userFileService.getOneFile(filter);

			if (file != null && userFileService.restoreFile(file.getUserfileId())) {
				result.setStatusCode(200);
				result.setMessage("还原成功");
			} else {
				result.setStatusCode(500);
				result.setMessage("还原失败");
			}
		} catch (Exception e) {
			result.setStatusCode(500);
			result.setMessage("还原失败");
			e.printStackTrace();
		}

		return result;
	}

	/**
	 * 新建文件夹
	 */
	@GetMapping("mkdir")
	public Object mkdir(@RequestParam("dirname") String dirname, @RequestParam("path") String path,
			HttpSession session) {

		User user = (User) session.getAttribute("user");
		ResultObj result = new ResultObj();

		try {
			UserFile file = userFileService.getOneFileByPath(path);

			if (file == null) {
				result.setStatusCode(404);
				result.setMessage("父文件夹不存在");
				return result;
			}

			UserFile userFile = new UserFile();
			userFile.setFatherId(file.getUserfileId());
			userFile.setFileName(dirname);
			userFile.setFileType(false);
			userFile.setUserId(user.getUserId());
			if (userFileService.insertFile(userFile)) {
				result.setData(userFile);
				result.setStatusCode(200);
				result.setMessage("创建成功");
			} else {
				result.setStatusCode(500);
				result.setMessage("创建失败");
			}
		} catch (Exception e) {
			result.setStatusCode(500);
			result.setMessage("创建失败");
			e.printStackTrace();
		}

		return result;
	}

	/**
	 * 搜索文件
	 */
	@GetMapping("search")
	public Object search(@RequestParam(name = "sortOrder", required = false, defaultValue = "ASC") String sortOrder,
			@RequestParam(name = "sortColumn", required = false, defaultValue = "filename") String sortColumn,
			@RequestParam("filename") String filename, HttpSession session) {
		User user = (User) session.getAttribute("user");
		ResultObj result = new ResultObj();

		if (StringUtil.isEmpty(filename)) {
			result.setStatusCode(400);
			result.setMessage("参数错误");
			return result;
		}

		try {
			UserFile filter = new UserFile();
			filter.setIsDelete(false);
			filter.setFileType(true);
			filter.setSearchOption(filename);
			filter.setUserId(user.getUserId());
			fixFilter(filter);
			result.setData(userFileService.getAllFiles(filter));
			result.setMessage("获取成功");
			result.setStatusCode(200);
		} catch (Exception e) {
			result.setStatusCode(500);
			result.setMessage("获取失败");
			e.printStackTrace();
		}

		return result;
	}

	/**
	 * 重命名
	 */
	@GetMapping("rename")
	public Object rename(@RequestParam("userfileId") Long userfileId, @RequestParam("newName") String newName,
			HttpSession session) {
		User user = (User) session.getAttribute("user");
		ResultObj result = new ResultObj();

		if (StringUtil.isEmpty(newName)) {
			result.setStatusCode(400);
			result.setMessage("参数错误");
			return result;
		}

		UserFile userFile = new UserFile();
		userFile.setUserId(user.getUserId());
		userFile.setUserfileId(userfileId);
		userFile.setFileName(newName);
		userFile.setIsDelete(false);

		try {
			if (userFileService.updateUserFile(userFile)) {
				result.setStatusCode(200);
				result.setMessage("更新成功");
				return result;
			}

			result.setStatusCode(404);
			result.setMessage("更新失败");
		} catch (Exception e) {
			result.setStatusCode(500);
			result.setMessage("更新失败");
			if (!(e instanceof org.springframework.dao.DuplicateKeyException)) {
				e.printStackTrace();
			}
		}

		return result;
	}

	private void fixFilter(UserFile filter) {
		if ("DESC".equalsIgnoreCase(filter.getSortOrder())) {
			filter.setSortOrder("DESC");
		} else {
			filter.setSortOrder("ASC");
		}

		if ("filename".equalsIgnoreCase(filter.getColumnName())) {
			filter.setColumnName("file_name");
		} else if ("filesize".equalsIgnoreCase(filter.getColumnName())) {
			filter.setColumnName("file_size");
		} else if ("uploadtime".equalsIgnoreCase(filter.getColumnName())) {
			filter.setColumnName("upload_time");
		}
	}

}
